<template>
  <div>
    opfs text
    <img :src="src" />
    {{ src }}
  </div>
</template>
<script setup lang="ts">
import VConsole from "vconsole";
import { write, file, dir } from "opfs-tools";
import { ref } from "vue";

new VConsole({ theme: "dark" });

const downUrl = "https://project-star.oss-cn-beijing.aliyuncs.com/assets/b838f78f4293f025c95c7b56dc3877a7.jpg";

const src = ref("");
init();
async function init() {
  src.value = await getUrl(downUrl);
}

async function getUrl(url) {
  try {
    const lurl = new URL(url);
    const DIRFIX = "/star";
    const isexists = await dir(DIRFIX).exists();
    if (!isexists) {
      await dir(DIRFIX).create();
    }
    const LOCA_PATH = DIRFIX + lurl.pathname;
    const isLocalPathExists = await file(LOCA_PATH).exists();
    if (!isLocalPathExists) {
      fetch(downUrl).then(async (res) => {
        try {
          const blop = await res.blob();
          write(LOCA_PATH, await blop.arrayBuffer());
        } catch (error) {
          console.log(error);
        }
      });
      return url;
    }

    const buffer = await file(LOCA_PATH).arrayBuffer();
    const blob = new Blob([buffer]);
    const localurl = URL.createObjectURL(blob);
    return localurl;
  } catch (error) {
    console.log(error);
    return url;
  }
}
</script>
<style scoped lang="less"></style>
